package model;

import java.util.Observable;	

/**
 * 
 * @author Michael & Pierre
 *
 */
/**
 * Model used to manage the state of the system
 */
public class SystemState extends Observable {
	
	/**
	 * Current state of the system
	 */
	private State currentState;
	/**
	 * True if the system has been initialized
	 */
	private boolean init=false;
	
	public SystemState() {
		currentState = State.disconnected;
	}
    
	/**
	 * Method called to change the state
	 * @param s next state of the system
	 * @throws StateChangeException
	 */
	public void changeState(State s) throws StateChangeException{
		switch (s) {
		case disconnected:
			// Necessaire � l'initialisation du chat
			if (currentState == State.disconnected && !init) {
				init = true;
				currentState = s;
				setChanged();
				notifyObservers(s); break;
			}
			if (currentState == State.disconnecting) {
				currentState = s;
				setChanged();
				notifyObservers(s); break;
			}	
		
		case connected:
			if (currentState == State.disconnected || currentState == State.busy) {
				currentState = s;
				setChanged();
				notifyObservers(s); break;
			}	
		
		case busy:
			if (currentState == State.busy){
				throw new StateChangeException("File transfer already in progress...");
			}
			else if (currentState == State.connected) {
				currentState = s;
				setChanged();
				notifyObservers(s); break;
			}
			
		case disconnecting:
			if (currentState == State.connected) {
				currentState = s;
				setChanged();
				notifyObservers(s); break;
			}
			
		// Lorsque l'utilisateur ferme la fenetre sans passer par la deconnexion
		case closing:
			if (currentState == State.busy) {
				throw new StateChangeException("Cannot close now. File transfer in progress..."); 
			}
			else if (currentState != State.disconnected) {
				changeState(State.disconnecting); 
			}
			currentState = s;
			setChanged();
			notifyObservers(s); break;
		}	
	}
	
	public State getCurrentState(){
		return currentState;
	}
}
